package com.iye.puretennis.helper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.iye.puretennis.domain.CacheType;
import com.iye.puretennis.domain.User;
import com.iye.puretennis.domain.UserToken;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/12.
 */
public class DBManager {
    private SQLiteDatabase db;

    public DBManager(Context context) {
        DBHelper helper = new DBHelper(context);
        db = helper.getWritableDatabase();
    }

    /**
     * after login the app,some data need to be stored
     *
     * @param guid  the guid of the user
     * @param token the access token to remote server
     */
    public void login(String guid, String token, int setup) {
        db.execSQL("insert into " + DBHelper.TABLE_USER_TOKEN + " values(null,?,?,?,null,null)", new Object[]{guid, token, setup});
    }

    /**
     * logout and remove the login data
     */
    public void logout() {
        String guid = retrieveCurrentUser().getGuid();
        db.execSQL("delete from mycaches where userguid=? and cachetype=?", new String[]{guid, CacheType.USER_ALIAS.name()});
        db.execSQL("delete from usertoken");
    }

    public UserToken retrieveCurrentUser() {
        Cursor cursor = db.rawQuery("select guid,token,setup,latitude,longitude from usertoken", new String[]{});
        if (cursor.moveToFirst()) {
            String guid = cursor.getString(0);
            String token = cursor.getString(1);
            boolean setup = cursor.getInt(2) == 1;
            String latitude = cursor.getString(3);
            String longitude = cursor.getString(4);
            return new UserToken(guid, token, setup, latitude, longitude);
        }
        return null;
    }

    /**
     * retrieve user by token
     *
     * @return
     */
    public User retrieveUser(String token) {
        Cursor cursor = db.rawQuery("select guid,token from user where token=?", new String[]{token});
        if (cursor.moveToFirst()) {
            String guid = cursor.getString(0);
            return new User(guid, token);
        }
        return new User();
    }

    public void addIdols(String idolsJson) {
        db.execSQL("insert into " + DBHelper.TABLE_USER + " values(null,?)", new Object[]{idolsJson});
    }

    public void cacheMyData(String cacheType, String jsonStr) {
        String guid = retrieveCurrentUser().getGuid();
        db.execSQL("insert into " + DBHelper.TABLE_MYCACHES + " values(null,?,?,?)", new Object[]{guid, cacheType, jsonStr});
    }

    public void cacheChatMessage(String friendGuid, String jsonStr) {
        String guid = retrieveCurrentUser().getGuid();
        db.execSQL("insert into " + DBHelper.TABLE_CHAT_MESSAGE + " values(null,?,?,?)", new Object[]{guid, friendGuid, jsonStr});
    }

    public String retrieveMyCachedData(String cacheType) {
        UserToken userToken = retrieveCurrentUser();
        if (userToken != null) {
            String guid = userToken.getGuid();
            Cursor cursor = db.rawQuery("select content from mycaches where userguid=? and cachetype=?", new String[]{guid, cacheType});
            if (cursor.moveToFirst()) {
                return cursor.getString(0);
            }
        }
        return null;
    }

    public List<String> retrieveChatMessage(String friendGuid) {
        List<String> messages = new ArrayList<String>();
        UserToken userToken = retrieveCurrentUser();
        if (userToken != null) {
            String guid = userToken.getGuid();
            Cursor cursor = db.rawQuery("select message from "+DBHelper.TABLE_CHAT_MESSAGE+" where userguid=? and identifier=?", new String[]{guid, friendGuid});
            while (cursor.moveToNext()) {
                String messageAsString = cursor.getString(0);
                messages.add(messageAsString);
            }
            Collections.reverse(messages);
            return messages;
        }
        return null;
    }

    public void updateMyCachedData(String cacheType, String jsonStr) {
        String guid = retrieveCurrentUser().getGuid();
        ContentValues columns = new ContentValues();
        columns.put("content", jsonStr);
        db.update("mycaches", columns, "userguid=? and cachetype=?", new String[]{guid, cacheType});
    }

    public void updateUserLocation(String latitude, String longitude) {
        String guid = retrieveCurrentUser().getGuid();
        ContentValues columns = new ContentValues();
        columns.put("latitude", latitude);
        columns.put("longitude", longitude);
        db.update("usertoken", columns, "guid=?", new String[]{guid});
    }
}
